package xyz.thoughtset.viewer.ai.mcp.client.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xyz.thoughtset.viewer.ai.mcp.client.dao.McpBotInfoDao;
import xyz.thoughtset.viewer.ai.mcp.client.entity.McpBotInfo;
import xyz.thoughtset.viewer.ai.mcp.client.factory.McpBotFactory;
import xyz.thoughtset.viewer.common.core.constants.StatusCodeConstant;
import xyz.thoughtset.viewer.common.core.entity.BaseMeta;
import xyz.thoughtset.viewer.common.crud.core.service.BaseServiceImpl;
import xyz.thoughtset.viewer.modules.datarel.entity.DataRel;
import xyz.thoughtset.viewer.modules.datarel.service.DataRelService;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@DependsOn("mcpBotFactory")
//@Transactional
public class McpBotInfoServiceImpl extends BaseServiceImpl<McpBotInfoDao, McpBotInfo> implements McpBotInfoService {

    @Autowired
    protected McpBotFactory mcpBotFactory;


    @EventListener(ApplicationReadyEvent.class)
    public void initData() {
        mcpBotFactory.createMcpServer(workingBots());
    }

    @Override
    public McpBotInfo saveData(McpBotInfo data) {
        mcpBotFactory.removeClient(data.getId());
        data.setStatesCode(StatusCodeConstant.EDITING);
        return super.saveData(data);
    }

    @Override
    @Transactional
    public boolean deleteById(String pkey) {
        super.deleteById(pkey);
        unpublishedServer(pkey);
        return true;
    }

    @Override
    @Transactional
    public void unpublishedServer(String serverId) {
        baseMapper.updateById(new McpBotInfo(serverId, StatusCodeConstant.EDITING));
        mcpBotFactory.removeClient(serverId);
    }

    @Override
    public List<McpBotInfo> workingBots() {
        QueryWrapper<McpBotInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(McpBotInfo::getStatesCode, StatusCodeConstant.RUNNING)
                .ne(McpBotInfo::getTypeCode,"")
                .isNotNull(McpBotInfo::getTypeCode)
                .orderByAsc(McpBotInfo::getOrderNum);
        return baseMapper.selectList(queryWrapper);
    }

    @SneakyThrows
    @Override
    @Transactional
    public void publishServer(String serverId) {
        McpBotInfo botInfo = baseMapper.selectById(serverId);
        baseMapper.updateById(new McpBotInfo(serverId, StatusCodeConstant.RUNNING));
        mcpBotFactory.createMcpServer(botInfo);
    }



}
